package cn.exrick.xboot.modules.your;


import java.util.Date;
import java.util.Random;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: njp
 * @Date: 2020/05/27/9:58
 * @Description: 自定义任务
 */
public class MyThread implements Runnable {
    private Random random = null;

    public MyThread() {
        random = new Random();
    }
    @Override
    public void run() {
        try {
            System.out.println("任务执行开始:" + new Date());
            /**使用随机延时[0-3]秒来模拟执行任务*/
            int sleepNumber = random.nextInt(3);
            TimeUnit.SECONDS.sleep(sleepNumber);
            System.out.println("任务执行完毕:" + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        /**使用Executors工具快速构建对象*/
        ScheduledExecutorService scheduledExecutorService =
                Executors.newScheduledThreadPool(1);
        System.out.println("3秒后开始执行计划线程池服务..." + new Date());
        scheduledExecutorService.schedule(new MyThread(), 3, TimeUnit.SECONDS);
    }

    public static void timeOut(int seconds){
         /**使用Executors工具快速构建对象*/
        ScheduledExecutorService scheduledExecutorService =
                Executors.newScheduledThreadPool(1);
        System.out.println(seconds+"秒后开始执行计划线程池服务..." + new Date());
        scheduledExecutorService.schedule(new MyThread(), seconds, TimeUnit.SECONDS);
    }
}



